/**
 * https://leetcode-cn.com/problems/range-sum-query-immutable/submissions/
 * 区域和检索
 */
class NumArray {
    private cache: number[] = []
    constructor(public nums: number[]) {
        const len = nums.length;
        let t = 0
        for (let i = 0; i < len; i++) {
            t += nums[i]
            // 存储i之前的总和
            this.cache.push(t)
        }
    }

    sumRange(left: number, right: number): number {
        // 要加上left项本身
        return this.cache[right] - this.cache[left] + this.nums[left]
        
    }
}



class NumArray2 {
    private arr: number[]
    constructor(nums: number[]) {
        this.arr = nums;
    }

    sumRange(left: number, right: number): number {
        let ans = 0,
            arr = this.arr;

        // 求[left, right]的总和
        for (let i = left; i <= right; i++) {
            ans += arr[i]
        }

        return ans;
    }
}
